package com.ssm.basis.service.config.aop;

import lombok.RequiredArgsConstructor;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * 事务切面，自动为 service 层方法添加事务
 */
@RequiredArgsConstructor
// @Configuration(proxyBeanMethods = false)
class TransactionAdvice {
    static final String TX_ADVICE_NAME = "txAdvice";
    final DataSourceTransactionManager transactionManager;

    @Bean(TX_ADVICE_NAME)
    TransactionInterceptor txAdvice() { // 创建事务通知
        Properties properties = new Properties();
        properties.setProperty("get*", "PROPAGATION_NOT_SUPPORTED,-Exception,readOnly");
        properties.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("save*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
        transactionInterceptor.setTransactionManager(transactionManager);
        transactionInterceptor.setTransactionAttributes(properties);
        return transactionInterceptor;
    }

    @Bean
    BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        // creator.setProxyTargetClass(true);
        creator.setInterceptorNames(TX_ADVICE_NAME);
        creator.setBeanNames("*Service", "*ServiceImpl");
        creator.setProxyTargetClass(true);
        return creator;
    }
}
